<?php
class articleController extends Controller{
	public function index(){
		$p = G('p') ? G('p') : 1;
		$total = $this->model->count_articles();
		$itemPerPage = 2;
		$page = load_util('Page');
		$pages = $page->init(array('currentPage'=>$p,'totalItems'=>$total,'itemPerPage'=>$itemPerPage));
		if( $pages ){
			$this->assign('pages', $pages);
			$start = ($p-1)*$itemPerPage;
			$limit = $start .','. $itemPerPage;
		}
		$list = $this->model->get_articles('','',$limit);
		$this->assign('list', $list);
		$this->display('admin/articles.html');
	}

	public function add(){
		if( G('save')==1 ){
			$data = get_data();
			$data['author'] = 1;
			$data['addtime'] = time();
			$data['abstract'] = substring(strip_tags($data['content']), 0, 200);
			$rs = $this->model->add($data);
			if( is_int($rs) && $rs>0 ){
				ajax_return(array('status'=>1));
			}else{
				ajax_return(array('status'=>0)); 
			}
			exit;
		}
		$catModel = load_model('artCategory');
		$cats = $catModel->get_categories();
		$cats = tree($cats);
		$this->assign('cats', $cats);
		$this->display('admin/addArticle.html');	
	}

	public function edit(){
		if( G('save')==1 ){
			$data = get_data();
			$data['addtime'] = time();
			$data['abstract'] = substring(strip_tags($data['content']), 0, 200);
			$rs = $this->model->edit($data['id'],$data);
			if( is_int($rs) && $rs>0 ){
				ajax_return(array('status'=>1));
			}else{
				ajax_return(array('status'=>0)); 
			}
			exit;
		}
		$id = G('id');
		$id =  intval($id);
		if( empty($id) ){
			alert('非法ID');
			exit;
		}
		$art = $this->model->get_article($id);
		if( empty($art) ){
			alert('未找到该文章记录');
			exit;
		}
		$this->assign('art', $art);
		$catModel = load_model('artCategory');
		$cats = $catModel->get_categories();
		$cats = tree($cats);
		$this->assign('cats', $cats);
		$this->display('admin/editArticle.html');	
	}

	public function del(){
		$id = intval(G('id'));
		if( empty($id) ){
			ajax_return(array('status'=>0));
			exit;
		}
		$rs = $this->model->del($id);
		ajax_return(array('status'=>$rs));
		exit;
	}

	public function upload(){
		$upload = load_util('Upload');	
		$config = array(
			'save_path'=> __UPLOAD__.'article/'
			);	
		$upload->config($config);
		$rs = $upload->save();
		if( $rs!==false ){
			$rs = json_decode($rs,true);
			$file = UPLOAD_URL.'article/'.$rs[0]['saveName'];
			$title = htmlspecialchars($_POST['pictitle'], ENT_QUOTES);
			$state = "SUCCESS";
			echo "{'url':'".$file."','title':'".$title."','state':'".$state."'}";
		}else{
			$state = "FAILED ".$upload->get('error');
			echo "{'url':'".$file."','title':'".$title."','state':'".$state."'}";
		}
	}
	
}
